package com.m3958.firstgwt.server.command;

import java.io.IOException;

import net.sf.json.JSONObject;

import com.google.inject.Inject;
import com.m3958.firstgwt.client.types.SmartSubOperationName;
import com.m3958.firstgwt.server.exception.SmartJpaException;
import com.m3958.firstgwt.server.model.BaseModel;
import com.m3958.firstgwt.server.model.TableSchema;
import com.m3958.firstgwt.server.response.ErrorMessageResponse;
import com.m3958.firstgwt.server.service.ClojureService;
import com.m3958.firstgwt.server.types.SmartError;

public class AddCommand extends BaseCommand implements Command{
	
	private boolean writeResponse = true;
	
	@Inject
	private ClojureService clojureService;
	
	JSONObject result = null;
	
	@Override
	public void execute() throws SmartJpaException, IOException{
		SmartSubOperationName sson = SmartSubOperationName.NO_SUB_OPERATION;
		if(reqPs.getSubOpType() != null)
			sson = SmartSubOperationName.valueOf(reqPs.getSubOpType());
		
		switch (sson) {
		default:
			result = smartAdd();
		}
		if(writeResponse){
			JSONObject m3958jo = new JSONObject();
			m3958jo.element("tid", reqPs.getTid());
			if(!errors.isEmpty()){
				result = injector.getInstance(ErrorMessageResponse.class).getJsonObject();
			}
			result.getJSONObject("response").element("m3958extra", m3958jo);
			
			if(reqPs.isJsonp()){
				autils.writeJsonpResponse(res, result.toString(), reqPs.getStringValue("callback"));
			}else{
				if(reqPs.isIframe()){
					irss.addIframeResult(reqPs.getTid(), result.toString());
					autils.writeHtmlResponseWithTemplate(res, "", "");
				}else{
					autils.writeJsonResponse(res,result.toString());
				}
			}
		}
			
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JSONObject smartAdd() throws SmartJpaException{
		if("com.m3958.firstgwt.server.model.FreeRecord".equals(reqPs.getModelName())){
			return clojureAdd();
		}
		BaseModel model = getBaseModelFromParams();
		getDao().smartPersistBaseModel(model);
		return autils.getListResponse(model,reqPs.getJsonv());
	}
	/**
	 * 必须传入当前的tableschema，还有req
	 * @return
	 */
	private JSONObject clojureAdd() {
		TableSchema ts = emp.get().find(TableSchema.class, reqPs.getTableschemaid());
		if(ts == null){
			errors.addError(new SmartError("必须提供表单结构Id号！", 0));
			return null;
		}
//		return autils.getListResponse(JSONObject.fromObject(clojureService.getAddResult(req,ts)), reqPs.getJsonv());
		return JSONObject.fromObject(clojureService.getAddResult(req,ts));
	}

	@Override
	public String getResult() {
		return result.toString();
	}

	@Override
	public void execute(boolean writeResponse) throws SmartJpaException,
			IOException {
		this.writeResponse = writeResponse;
		execute();
	}

}
